import skinparse from './skinparse'
export default class Component extends PIXI.Container{
    constructor() {
        super();
    }

    setSkinFromurl(url) {
        let data = Application.app.loader.resources[url].data;
        this.setSkin(data)
    }

    setSkin(data) {
        if (data) {
            let skin = null;
            if (typeof data == "function") {
                skin = new data(); 
            } else if (typeof data == "string") {
                if (data.indexOf(".json") > 0) {
                    // todo 去加载资源
                } else {
                    if (typeof window[data] == "function") {
                        skin = new window[data]
                    } else {
                        
                    }
                }
            } else {
                if (data.node) {
                    skin = skinparse.createSkin(data);
                } else {
                    console.error("不能解析该皮肤:", data)
                }
            }
            if (skin) {
                this._parseskin(skin);
            }
        }
    }

    // skin.width, skin.height, skin.name, skin.elements
    _parseskin(skin) {
        this.removeChildren();
        this.states = {};
        if (skin) {
            this._addSkinDisplay(skin, this)
            for (let key in skin.idMap) {
                this[key] = skin.idMap[key];
            }
            skin.idMap = null;
            this.emit("complete");
        }
    }

    _addSkinDisplay(skin, parent) {
        let count = skin.children ? skin.children.length : 0;
        for (let i = 0; i < count; i++) {
            let element = skin.children[i];
            if (element.id) {
                if (this[element.id]) {
                    console.warn("不能有重复的id:", element.id)
                }
                this[element.id] = element;
            }
            if (element.children && element.children.length > 0) {
                this._addSkinDisplay(element, element);
            } 
            parent.addChild(element);
        }
    }
}